require 'digest/sha1'

## 
# this model expects a certain database layout and its based on the 
# name/login pattern. 
class User < ActiveRecord::Base
	belongs_to :group
	has_many :user_answers
	has_many :exam_results
  has_many :images

  ##
  # Tries to authenticate the user
  # @param login is the username of the user
  # @param pass is the password (in cleartext) of the user
  # @return a user-object is returned if it was successful, otherwise nil is 
  #         returned
  def self.authenticate(login, pass)
    find_first(["login = ? AND password = ?", login, sha1(pass)])
  end  

  ##
  # this method changes the password of an user
  def change_password(pass)
    update_attribute "password", self.class.sha1(pass)
  end
    
  protected

  ##
  # This method applies the sha1 algorithm to the passed parameter
  # @param pass is a string
  # @return the sha1 applied string is returned
  def self.sha1(pass)
    Digest::SHA1.hexdigest("change-me--#{pass}--")
  end
    
  before_create :crypt_password
  
  ##
  # encrypts the password
  def crypt_password
    write_attribute("password", self.class.sha1(password))
  end

  validates_length_of :login, :within => 2..40
  validates_length_of :password, :within => 3..40
  validates_presence_of :login, :password, :password_confirmation
  validates_uniqueness_of :login, :on => :create
  validates_confirmation_of :password, :on => :create     
end
